package service

import (
	"errors"

	"publish-manage/internal/model"
	"publish-manage/pkg/database"
	"publish-manage/pkg/domain"
)

var PackageVersionService = new(packageVersionService)

type packageVersionService struct{}

func (_ *packageVersionService) Get(instance *model.PackageVersion) (*model.PackageVersion, error) {
	if instance.Id == "" {
		return nil, errors.New("id不能为空")
	}

	if exist, err := database.DB.Get(instance); err != nil {
		return nil, err
	} else if !exist {
		return nil, nil
	}
	return instance, nil
}

func (_ *packageVersionService) List(condition *model.PackageVersion, offset, limit int, orderBy string) (pageInfo *domain.Paginate, err error) {
	// 处理不允许查询的字段

	// 处理sql
	session := database.DB.NewSession()
	if limit > -1 && offset > -1 {
		session.Limit(limit, offset)
	}

	if orderBy != "" {
		session.OrderBy(orderBy)
	}
	session.Desc("create_time")

	// 模糊查找
	if condition.Path != "" {
		session.Where("path like ?", condition.Path+"%")
		condition.Path = ""
	}

	var list []*model.PackageVersion
	total, err := session.FindAndCount(&list, condition)
	if err != nil {
		return nil, err
	}

	return &domain.Paginate{
		Total:  int(total),
		Offset: offset,
		Limit:  limit,
		Items:  list,
	}, nil
}

func (_ *packageVersionService) GetLatest(packageId string) (*model.PackageVersion, error) {
	pv := &model.PackageVersion{PackageId: packageId}
	if exist, err := database.DB.Get(pv); err != nil {
		return nil, err
	} else if !exist {
		return nil, nil
	}
	return pv, nil
}
